<?php
//error_reporting(0);
date_default_timezone_set("UTC");

//include(__DIR__.'/file.php');
require_once($_SERVER['DOCUMENT_ROOT']."/lib/config.php");
require_once($_SERVER['DOCUMENT_ROOT']."/lib/functions.php");
require_once($_SERVER['DOCUMENT_ROOT']."/lib/pdomanager.php");
require_once($_SERVER['DOCUMENT_ROOT']."/lib/paginate_class.php");
/*

require_once "../lib/config.php";
require_once "../lib/functions.php";
require_once "../lib/pdomanager.php";
require_once "../lib/paginate_class.php";


*/
include_once("CommonFeatures.php");

/**
 * responseWithErrorCode()
 * 
 * @param mixed $returnCode
 * @return
 */

class PerformPostAction extends PostAction{
    
    //public $postAction;
    private $loggedInUserId=0;
    public $pdodbobj;
    public $connstatus=false;
    public $lastInsertedID=0;
    function __construct() {
       try{
            $this->pdodbobj= new DB();
            $this->connstatus=$this->pdodbobj->connect();
            
            if(isset($_SESSION['Allyfolio_User_ID'])&& !empty($_SESSION['Allyfolio_User_ID']) && is_numeric($_SESSION['Allyfolio_User_ID'])){
                $this->loggedInUserId=trim($_SESSION['Allyfolio_User_ID']);    
            }
            else{
                die('PerformPostAction:__construct():: Invalid Session => '.$_SESSION['Allyfolio_User_ID'].' \t'. "\n");
            }
        }
        catch(Exception $ex){
            die('PerformPostAction:__construct():: \t'. $ex->getMessage(). "\n");   
        }
   }
        
    //check if user is authorised by comparining passed userid with session id
    /**
     * PerformPostAction::isAuthenticated()
     * 
     * @param mixed $userId
     * @return
     */
    public function isAuthenticated($userId){
        //global $loggedInUserId;
        if(isset($userId) && !empty($userId)  && is_numeric($userId) && $this->loggedInUserId==$userId){
            return true;
        }
        else{
            return false;
        }
    }
    /**
     PostData : used to post any data with privacy setting, userid, and enumerated post type
     
     Result: PostAction::Contants (default: PostAction::Failure ==> 200)
     * 
     */
    function PostData($postedTitle,$postcontent,$userId,$postType=PostType::Default_Type,$privacyType=PrivacySettings::DefaultSetting,$parentID=0, $clusteredId=0,$sharedPostId=0,$shareadditionalmsg="",$sharedPostwithtypeid=0,$postlocation="",$taggedinUsers="",$postMedias="",$emotionstextstr=""){
        //echo ("Parameters: postcontent:".$postcontent."\t Userid:".$userId."\t postType:".$postType."\t privacyType: ".$privacyType);
        
        $postAction= new PostAction();
        $actionRes = $postAction->Failure;
        try{
            //echo "<br>-->  doing stuff-->";
            //do your stuff
            if(PerformPostAction::isAuthenticated($userId)){
                //echo "<br>-->  logged in -->";
                $insertdataarr=array(
                                     "User_ID"=>$userId,
                                     "Privacy_Type_ID"=>$privacyType,
                                     "Clustered_ID"=>$clusteredId,
                                     "Post_Title"=>$postedTitle,
                                     "PostedContent"=>$postcontent,
                                     "Post_Type_ID"=>$postType,
                                     "Total_Likes"=>0,
                                     "Total_Shares"=>0,
                                     "Posted_On_Date"=>strtotime(date("Y-m-d H:i:s", time())),
                                     "Last_Modified_Date"=>strtotime(date("Y-m-d H:i:s", time())),
                                     "Shared_Post_ID"=>$sharedPostId,
                                     "Parent_ID"=>$parentID,
                                     "sharing_msg"=>$shareadditionalmsg,
                                     "shared_with_type_id"=>$sharedPostwithtypeid,
                                     "post_location"=>$postlocation,
                                     "Friend_IDs"=>$taggedinUsers,
                                     "postedemotion"=>$emotionstextstr,
                                     "Status"=>1
                                     );
                
                if($this->pdodbobj!=null){// check if connection object is set to connection
                    $this->pdodbobj->insertData("af_user_posts_activities",$insertdataarr);
                    if($this->pdodbobj->affectedrows>0)
                    {
                        $this->lastInsertedID= $this->pdodbobj->last_id();

                        //check emdia exist or not
                        if($postMedias!="")
                        {
							//Move image from temap to orig folder
                        	$arrMedias=explode(",",$postMedias);
                        	for($mediaCounter=0;$mediaCounter<count($arrMedias);$mediaCounter++)
                        	{
                        		if($arrMedias[$mediaCounter]!="")
								{
									$ext = explode('.', $arrMedias[$mediaCounter]);
									if(in_array(strtolower($ext[count($ext)-1]),array("jpg","jpeg","png","bmp","gif","vob","mp4","3gp")))
									{
										$targetFilePath="../".str_replace("temp_post_media","post_media",$arrMedias[$mediaCounter]);

										$targetPathArr=explode("/",$targetFilePath);
										//print_r($targetPathArr);
										$targetPathArr[count($targetPathArr)-1]="";
										$target_path=implode("/",$targetPathArr);

										if(!file_exists($target_path))
								        {
											mkdir($target_path,0777);
										}

										if(copy("../".$arrMedias[$mediaCounter],$targetFilePath))
										{
											if(in_array(strtolower($ext[count($ext)-1]),array("jpg","jpeg","png","bmp","gif")))
											{
												$mediaType="IMAGE";
											}
											else if(in_array(strtolower($ext[count($ext)-1]),array("vob","mp4","3gp")))
											{
												$mediaType="VIDEO";
											}
											else if(in_array(strtolower($ext[count($ext)-1]),array("mp3")))
											{
												$mediaType="AUDIO";
											}
											//Insert data in DB	
											$mediaDataArr=array(
			                                     "Post_ID"=>$this->lastInsertedID,
			                                     "Media_Path"=>str_replace("../","",$targetFilePath),
			                                     "Media_Type"=>$mediaType,
			                                     "Status"=>1
                                     		);
											$this->pdodbobj->insertData("af_user_posts_media_uploads",$mediaDataArr);
											
										}
									}
								}
							}
							
							
							
							
							
						}
                         $actionRes=$postAction->Success;     
                    }
                    else{
                        $actionRes=$postAction->Failure;
                    }
                }
                else{
                    $actionRes=$postAction->Failure;
                    $actionRes["msg"]="Unable to connect to db";
                }
//                $actionRes=$postAction->Success;
            }
            else{
                $actionRes=$postAction->Failed_For_Invalid_Session;
                //die('PerformPostAction:PostData():: Invalid UserId \t'."\n");
            }
            
        }
        catch(Exception $ex){
            $actionRes['msg']=$e->getMessage();
            //die('PerformPostAction:PostData():: \t'. $ex->getMessage(). "\n");   
        }
        return $actionRes;
    }
    
    public function getSourceActivityOwnerID($tblname,$returnFieldStr,$whereConditionstr){
        $postAction= new PostAction();
        $ownerid=0;
        $totalConditionsToApply=0;
        try{
            if($this->pdodbobj!=null){// check if connection object is set to connection
                $whereStr="";
                $totalConditionsToApply=count($whereConditionstr);
                $wCount=0;
                foreach($whereConditionstr as $key=>$value){
                    $wCount++;
                    if($wCount<$totalConditionsToApply){
                        $whereStr.=$key."=".$value." and ";
                    }   
                    else{
                        $whereStr.=$key."=".$value;
                    }
                }
                
                $selquery=" select ".$returnFieldStr." from ".$tblname." where ".$whereStr;                              
                $feedRecords= $this->pdodbobj->fetch_array($this->pdodbobj->query($selquery,array()));
                if(count($feedRecords)>0){
                    if(isset($feedRecords[0]) && is_array($feedRecords[0])){
                        $feedRecords=$feedRecords[0];
                        return $feedRecords[$returnFieldStr];
                    }
                }    
            }
        }
        catch(Exception $ex){
            $this->eLog->writeException('ReadFeedAction:getPostLikesCount():: Exception => '.$actionRes["msg"].' \t');
        }
        return $ownerid;
    }
    
    public function likePost($postId,$userId,$sourceDetails=array("TableName"=>"af_user_posts_activities","PKEY"=>"POST_ID","ACTIVITYOWNERID"=>"USER_ID")){
        $postAction= new PostAction();
        $actionRes=$postAction->Failure;
        $returnFieldStr="";
        $whereConditionstr="";
        $defaultSTbleName="";
        $defaultSTblePKEY="";
        $defaultSTbleUserID=0;
        try{
            //do your stuff
            if(PerformPostAction::isAuthenticated($userId)){
                //echo "<br>-->  logged in -->";
                $defaultSTbleName=$sourceDetails["TableName"];
                $defaultSTblePKEY=$sourceDetails["PKEY"];
                $returnFieldStr=$sourceDetails["ACTIVITYOWNERID"];
                $whereConditionstr=array($defaultSTblePKEY=>$postId);
                //$defaultSTbleUserID=$this->getSourceActivityOwnerID($defaultSTbleName,$returnFieldStr,$whereConditionstr);// $sourceDetails["ACTIVITYOWNERID"];
                $defaultSTbleUserID=$returnFieldStr;
                $insertdataarr=array(
                                     "Post_ID"=>$postId,                                     
                                     "Source_Table_Name"=>$defaultSTbleName,
                                     "Source_Table_PKEY"=>$defaultSTblePKEY,
                                     "Source_Activity_User_ID"=>$defaultSTbleUserID,
                                     "User_ID"=>$userId,
                                     "Like_Date"=>strtotime(date("Y-m-d H:i:s"))
                                     );
                $whereConditions=array(
                                     "Post_ID"=>$postId,                                     
                                     "Source_Table_Name"=>$defaultSTbleName,
                                     "Source_Table_PKEY"=>$defaultSTblePKEY,
                                     "Source_Activity_User_ID"=>$defaultSTbleUserID,
                                     "User_ID"=>$userId
                                     );
                //echo "<pre>";
//                print_r($insertdataarr);
//                echo "</pre>";
//                die();
                if($this->pdodbobj!=null){// check if connection object is set to connection
                
                    $isExist= $this->pdodbobj->checkExistance("af_user_post_likes",$whereConditions);
                    if($isExist==1)
                    {
                         $this->pdodbobj->deleteData("af_user_post_likes",$whereConditions); 
                    }
                    else{
                        $this->pdodbobj->insertData("af_user_post_likes",$insertdataarr);
                    }
                    
                    if($this->pdodbobj->affectedrows>0)
                    {
                         $actionRes=$postAction->Success;     
                    }
                    else{
                        $actionRes=$postAction->Failure;
                    }
                }
                else{
                    $actionRes=$postAction->Failure;
                    $actionRes["msg"]="Unable to connect to db";
                }
//                $actionRes=$postAction->Success;
            }
            else{
                $actionRes=$postAction->Failed_For_Invalid_Session;
                //die('PerformPostAction:PostData():: Invalid UserId \t'."\n");
            }
            
        }
        catch(Exception $ex){
            $actionRes['msg']=$e->getMessage();
            die('PerformPostAction:likePost():: \t'. $ex->getMessage(). "\n");   
        }
        return $actionRes;
    } 
    
    public function likeComment($postId,$commentId,$userId,$sourceDetails=array("TableName"=>"af_user_posts_comments","PKEY"=>"POST_ID","ACTIVITYOWNERID"=>"USER_ID")){
        $postAction= new PostAction();
        $actionRes=$postAction->Failure;
        $returnFieldStr="";
        $whereConditionstr="";
        $defaultSTbleName="";
        $defaultSTblePKEY="";
        $defaultSTbleUserID=0;
        try{
            //do your stuff
            if(PerformPostAction::isAuthenticated($userId)){
                //echo "<br>-->  logged in -->";
                $defaultSTbleName=$sourceDetails["TableName"];
                $defaultSTblePKEY=$sourceDetails["PKEY"];
                $returnFieldStr=$sourceDetails["ACTIVITYOWNERID"];
                $whereConditionstr=array($defaultSTblePKEY=>$postId);
                //$defaultSTbleUserID=$this->getSourceActivityOwnerID($defaultSTbleName,$returnFieldStr,$whereConditionstr);// $sourceDetails["ACTIVITYOWNERID"];
                $defaultSTbleUserID=$returnFieldStr;
                $insertdataarr=array(
                                     "Post_ID"=>$postId,
                                     "Comment_ID"=>$commentId,                                     
                                     "Source_Table_Name"=>$defaultSTbleName,
                                     "Source_Table_PKEY"=>$defaultSTblePKEY,
                                     "Source_Activity_User_ID"=>$defaultSTbleUserID,
                                     "User_ID"=>$userId,
                                     "Like_Date"=>strtotime(date("Y-m-d H:i:s"))
                                     );
                $whereConditions=array(
                                     "Post_ID"=>$postId,  
                                     "Comment_ID"=>$commentId,                                   
                                     "Source_Table_Name"=>$defaultSTbleName,
                                     "Source_Table_PKEY"=>$defaultSTblePKEY,
                                     "Source_Activity_User_ID"=>$defaultSTbleUserID,
                                     "User_ID"=>$userId
                                     );
                //echo "<pre>";
//                print_r($insertdataarr);
//                echo "</pre>";
//                die();
                if($this->pdodbobj!=null){// check if connection object is set to connection
                
                    $isExist= $this->pdodbobj->checkExistance("af_user_post_comments_likes",$whereConditions);
                    if($isExist==1)
                    {
                         $this->pdodbobj->deleteData("af_user_post_comments_likes",$whereConditions); 
                    }
                    else{
                        $this->pdodbobj->insertData("af_user_post_comments_likes",$insertdataarr);
                    }
                    
                    if($this->pdodbobj->affectedrows>0)
                    {
                         $actionRes=$postAction->Success;     
                    }
                    else{
                        $actionRes=$postAction->Failure;
                    }
                }
                else{
                    $actionRes=$postAction->Failure;
                    $actionRes["msg"]="Unable to connect to db";
                }
//                $actionRes=$postAction->Success;
            }
            else{
                $actionRes=$postAction->Failed_For_Invalid_Session;
                //die('PerformPostAction:PostData():: Invalid UserId \t'."\n");
            }
            
        }
        catch(Exception $ex){
            $actionRes['msg']=$e->getMessage();
            die('PerformPostAction:likePost():: \t'. $ex->getMessage(). "\n");   
        }
        return $actionRes;
    } 
    
    public function removePostComment($postId,$userId,$postCommentID){
        $postAction= new PostAction();
        $actionRes=$postAction->Failure;
        try{
            //do your stuff
            if(PerformPostAction::isAuthenticated($userId)){
                //echo "<br>-->  logged in -->";
                $deletedataarr=array(
                                     "Post_Id"=>$postId,
                                     "User_Comment_ID"=>$postCommentID
                                     );
                
                
                if($this->pdodbobj!=null){// check if connection object is set to connection
                    $this->pdodbobj->deleteData("af_user_posts_comments",$deletedataarr);
                    if($this->pdodbobj->affectedrows>0)
                    {
                         $actionRes=$postAction->Success;     
                    }
                    else{
                        $actionRes=$postAction->Failure;
                    }
                }
                else{
                    $actionRes=$postAction->Failure;
                    $actionRes["msg"]="Unable to connect to db";
                }
//                $actionRes=$postAction->Success;
            }
            else{
                $actionRes=$postAction->Failed_For_Invalid_Session;
                //die('PerformPostAction:PostData():: Invalid UserId \t'."\n");
            }
            
        }
        catch(Exception $ex){
            $actionRes['msg']=$e->getMessage();
            die('PerformPostAction:removePostComment():: \t'. $ex->getMessage(). "\n");   
        }
        return $actionRes;
    }
    
    public function commentPost($postId,$userId,$postComment,$taggedUsersArr,$uploadImgArr){
        $postAction= new PostAction();
        $actionRes=$postAction->Failure;
        try{
            //do your stuff
            if(PerformPostAction::isAuthenticated($userId)){
                //echo "<br>-->  logged in -->";
                $insertdataarr=array(
                                     "Post_Id"=>$postId,
                                     "User_Id"=>$userId,
                                     "Post_Comment"=>$postComment,
                                     "Comment_Date"=>strtotime(date("Y-m-d H:i:s")),
                                     "tagged_friends_email_ids"=>"'".implode("','",$taggedUsersArr)."'",
                                     "Status"=>1
                                     );
                
                
                if($this->pdodbobj!=null){// check if connection object is set to connection
                    $this->pdodbobj->insertData("af_user_posts_comments",$insertdataarr);
                    if($this->pdodbobj->affectedrows>0)
                    {
                        $lastCommentId= $this->pdodbobj->last_id();
                        $cinsertdataarr=array();
                        if(is_array($uploadImgArr) && count($uploadImgArr)>0){
                            foreach ($uploadImgArr as $ImgSrc) {
                                $cinsertdataarr=array(
                                         "Comment_ID"=>$lastCommentId,
                                         "Media_Path"=>$ImgSrc,
                                         "Media_Type"=>'IMAGE'
                                         );
                                $this->pdodbobj->insertData("af_user_posts_comments_media_uploads",$cinsertdataarr);
                            }
                        }
                        
                         $actionRes=$postAction->Success;     
                    }
                    else{
                        $actionRes=$postAction->Failure;
                    }
                }
                else{
                    $actionRes=$postAction->Failure;
                    $actionRes["msg"]="Unable to connect to db";
                }
//                $actionRes=$postAction->Success;
            }
            else{
                $actionRes=$postAction->Failed_For_Invalid_Session;
                //die('PerformPostAction:PostData():: Invalid UserId \t'."\n");
            }
            
        }
        catch(Exception $ex){
            $actionRes['msg']=$e->getMessage();
            die('PerformPostAction:commentPost():: \t'. $ex->getMessage(). "\n");   
        }
        return $actionRes;
    } 
    
    public function UploadPostMedia($postid,$postMediaPath,$mediaType){
        $postAction= new PostAction();
        $actionRes=$postAction->Failure;
        try{
            //do your stuff
            $insertdataarr=array(
                                 "Post_ID"=>$postid,
                                 "Media_Path"=>$postMediaPath,
                                 "Media_Type"=>$mediaType,
                                 "Status"=>1,
                                 "updated_date"=>strtotime("Y-m-d H:i:s")
                                 );
            
            if($this->pdodbobj!=null){// check if connection object is set to connection
                $this->pdodbobj->insertData("af_user_posts_media_uploads",$insertdataarr);
                if($this->pdodbobj->affectedrows>0)
                {
                     $actionRes=$postAction->Success;     
                }
                else{
                    $actionRes=$postAction->Failure;
                }
            }
            else{
                $actionRes=$postAction->Failure;
                $actionRes["msg"]="Unable to connect to db";
            }
            
        }
        catch(Exception $ex){
            $actionRes['msg']=$e->getMessage();
            die('PerformPostAction:UploadPostMedia():: \t'. $ex->getMessage(). "\n");   
        }
        return $actionRes;
    } 
    
    function UpdatePrivacySettings($userId,$privacyType=PrivacySettings::DefaultSetting,$updateSettingType="Default_Setting",$pclusterid=0){
        //echo ("Parameters: \t Userid:".$userId."\t privacyType: ".$privacyType);
        $postAction= new PostAction();
        $actionRes = $postAction->Failure;
        try{
            //do your stuff
            if(PerformPostAction::isAuthenticated($userId)){
                //query to update user privacy settings
                if($this->pdodbobj!=null){// check if connection object is set to connection
                    $appendStr="";
                    if(is_numeric($pclusterid) && $pclusterid>0){
                        $appendStr=",clusterid=".$pclusterid;
                    }
                    $updatequery="update af_user_privacy_settings set ".$updateSettingType."=".$privacyType." ".$appendStr." where User_ID=:User_ID";
                    $this->pdodbobj->query($updatequery,array(":User_ID"=>$userId));
                    if($this->pdodbobj->affectedrows>0)
                    {
                         $actionRes=$postAction->Success;
                         $actionRes["msg"]="Privacy setting updated";     
                    }
                    else{
                        $actionRes=$postAction->Failure;
                        $actionRes["msg"]="Failed to update privacy setting";
                    }
                }
                else{
                    $actionRes=$postAction->Failure;
                    $actionRes["msg"]="Unable to connect to db";
                }
            }
            else{
                $actionRes=$postAction->Failed_For_Invalid_Session;
                die('PerformPostAction:UpdatePrivacySettings():: Invalid UserId \t'."\n");
            }
            
        }
        catch(Exception $ex){
            $actionRes=$postAction->Failure;
            $actionRes['msg']=$e->getMessage();
            die('PerformPostAction:UpdatePrivacySettings():: \t'. $ex->getMessage(). "\n");   
        }
        return $actionRes;
    }
    
    public function updateFeedPrivacytype($userId,$feedID,$ptype,$clstrid,$allowedfrnd,$ignfrnd){
        $privacytype=$ptype;
        $clusterid=$clstrid;
        $allowedFriends=$allowedfrnd;
        $ignoredFriends=$ignfrnd;
        
        $postAction= new PostAction();
        $actionRes = $postAction->Failure;
        try{
            //echo "<br>-->  doing stuff-->";
            //do your stuff
            if(PerformPostAction::isAuthenticated($userId)){
                //echo "<br>-->  logged in -->";
                $insertdataarr=array(                                     
                                     "Privacy_Type_ID"=>$privacytype,
                                     "Clustered_ID"=>$clusterid,
                                     "ignore_friends"=>$ignoredFriends,
                                     "allowed_friends"=>$allowedFriends
                                     );
                                     
                $whereCondition=array(
                                        "Post_ID"=>$feedID,
                                        "User_ID"=>$userId
                                     );
                if($this->pdodbobj!=null){// check if connection object is set to connection
                    $this->pdodbobj->updateData("af_user_posts_activities",$insertdataarr,$whereCondition);
                    //$this->pdodbobj->insertData("af_user_posts_activities",$insertdataarr);
                    if($this->pdodbobj->affectedrows>0)
                    {
                         $actionRes=$postAction->Success;     
                    }
                    else{
                        $actionRes=$postAction->Failure;
                    }
                }
                else{
                    $actionRes=$postAction->Failure;
                    $actionRes["msg"]="Unable to connect to db";
                }
//                $actionRes=$postAction->Success;
            }
            else{
                $actionRes=$postAction->Failed_For_Invalid_Session;
                //die('PerformPostAction:PostData():: Invalid UserId \t'."\n");
            }
            
        }
        catch(Exception $ex){
            $actionRes['msg']=$e->getMessage();
            //die('PerformPostAction:PostData():: \t'. $ex->getMessage(). "\n");   
        }
        return $actionRes;
    }
    public function sharePost($postId,$userId,$sharedMsg){
        $postAction= new PostAction();
        $actionRes=$postAction->Failure;
        try{
            //do your stuff
            if(PerformPostAction::isAuthenticated($userId)){
                //echo "<br>-->  logged in -->";
                $insertdataarr=array(
                                     "post_id"=>$postId,
                                     "user_id"=>$userId,
                                     "comment"=>$postComment,
                                     "comment_date"=>strtotime("Y-m-d H:i:s")
                                     );
                
                if($this->pdodbobj!=null){// check if connection object is set to connection
                    $this->pdodbobj->insertData("af_post_comments",$insertdataarr);
                    if($this->pdodbobj->affectedrows>0)
                    {
                         $actionRes=$postAction->Success;     
                    }
                    else{
                        $actionRes=$postAction->Failure;
                    }
                }
                else{
                    $actionRes=$postAction->Failure;
                    $actionRes["msg"]="Unable to connect to db";
                }
//                $actionRes=$postAction->Success;
            }
            else{
                $actionRes=$postAction->Failed_For_Invalid_Session;
                //die('PerformPostAction:PostData():: Invalid UserId \t'."\n");
            }
            
        }
        catch(Exception $ex){
            $actionRes['msg']=$e->getMessage();
            die('PerformPostAction:commentPost():: \t'. $ex->getMessage(). "\n");   
        }
        return $actionRes;
    } 

}


//try{
//    $PerformPostAction=new PerformPostAction();
//    $PerformPostAction->PostData("hi sujeet", 1,1234,new PostType(PostType::Status_Updates));
//}
//catch(Execption $ex){
//    die('Caught exception: '. $e->getMessage(). "\n");
//}


?>